package com.rech.xbexpress3;

import com.rech.utils.OtherUtil;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.CountDownTimer;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;


import java.util.Timer;
import java.util.TimerTask;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class Kd1Activity extends AppCompatActivity {
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;

    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;

    private long mLastClickTime = 0;
    public static final long TIME_INTERVAL = 3000L;
    private CountDownTimer mTimer=null; //UI业务倒计时
    private static int adcount = 0;
    private final Handler mHideHandler = new Handler();

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar


        }
    };
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
        }
    };
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
        String orientation = sharedPreferences.getString("Orientation","");
        if (orientation.equals("landscape")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        setContentView(R.layout.activity_kd1);

        mVisible = true;getSupportActionBar().hide();
        //initTimer();

        ImageView welcome_gg = (ImageView) findViewById(R.id.kd1_gg);
        String cnImage     =  sharedPreferences.getString("CabinetType_gz","");
        new FetchUrlImageTask(cnImage,welcome_gg).execute();

        Button kd1_back = (Button)findViewById(R.id.kd1_back);
        kd1_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                setResult(4001, intent);
                finish();
            }
        });
        ImageView kd1_face = (ImageView)findViewById(R.id.kd1_face);
        kd1_face.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                long nowTime = System.currentTimeMillis();

                if (nowTime - mLastClickTime > TIME_INTERVAL) {
                    mLastClickTime = nowTime;
                    // do something
                    Intent intent = new Intent();
                    //intent.putExtra("sn", resultString);
                    setResult(4014, intent);
                    Exit();
                    finish();

                }
            }
        });
        Button kd1_reg = (Button)findViewById(R.id.kd1_reg);
        kd1_reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - mLastClickTime > TIME_INTERVAL) {
                    mLastClickTime = nowTime;
                    Intent intent = new Intent();
                    intent.setClass(Kd1Activity.this,KdRegActivity.class);
                    startActivityForResult(intent, 1);

                }
            }
        });

        Button kd1_login = (Button) findViewById(R.id.kd1_login);
        kd1_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - mLastClickTime > TIME_INTERVAL) {
                    mLastClickTime = nowTime;
                    EditText userEdit = findViewById(R.id.kd1_user);
                    String username = userEdit.getText().toString();
                    if(username.length() != 11 || !OtherUtil.isMobile(username))
                    {
                        Toast.makeText(Kd1Activity.this, "手机号不正确", Toast.LENGTH_LONG).show();
                        return ;
                    }

                    EditText passEdit = findViewById(R.id.kd1_pass);
                    String password = passEdit.getText().toString();
                    if(password.length() < 6)
                    {
                        Toast.makeText(Kd1Activity.this, "密码不能少于6位", Toast.LENGTH_LONG).show();
                        return ;
                    }
                    new FetchKDLoginTask(username,password).execute();

                }
            }
        });
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
    private void Exit(){
        unInitTimer();
        EventBus.getDefault().unregister(this);
    }
    @Override
    protected void onDestroy() {

        super.onDestroy();
    }
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mVisible = false;


    }

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar

        mVisible = true;


    }

    /**
     * Schedules a call to hide() in delay milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }
    private void unInitTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        //timer.cancel();
    }
    private void initTimer(){
        if (mTimer == null) {
            mTimer = new CountDownTimer((long) (180 * 1000), 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    if (!Kd1Activity.this.isFinishing()) {
                        adShow();
                    }
                }

                @Override
                public void onFinish() {
                    Log.e("zpan", "======onFinish=====");
                    Exit();
                    finish();
                }
            };
            mTimer.start();
        }
    }
    private void adShow(){
        if(adcount < 10){

            if(adcount == 0){
                adcount = 20;
                ImageView  welcome_gg = (ImageView) findViewById(R.id.kd1_gg);
                welcome_gg.setImageResource(R.mipmap.ad1);
            }
            adcount = adcount - 1;
        }
        if(adcount >= 10){

            if(adcount == 10){
                ImageView  welcome_gg = (ImageView) findViewById(R.id.kd1_gg);
                welcome_gg.setImageResource(R.mipmap.ad2);
            }
            adcount = adcount - 1;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        Intent intent = new Intent();
        switch(message.what){
            case 10400:
                handleKDLoginTask(message.obj);
                break;
            case 10401:
                Toast.makeText(Kd1Activity.this, "登录失败", Toast.LENGTH_SHORT).show();
                break;

        }
    }
    private void handleKDLoginTask(Object obj)
    {
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){

                String id = result.getJSONObject("data").getString("id");
                //String password = result.getJSONObject("data").getString("password");
                String username = result.getJSONObject("data").getString("username");
                //String token = result.getJSONObject("data").getString("token");
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putString("kd_id",id);
                //editor.putString("kd_password",password);
                editor.putString("kd_username",username);
                //editor.putString("kd_token",token);
                editor.apply();


                Intent intent = new Intent();
                //intent.putExtra("sn", resultString);
                setResult(4003, intent);
                Exit();
                finish();
            }else{
                View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle(result.getString("msg"));
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        dlg.dismiss();
                        t.cancel();
                    }
                }, 2000);

            }

        }catch(Exception e){
            View cv = getWindow().getDecorView();
            AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
            adbuilder.setTitle("网络异常");
            adbuilder.setMessage("2秒后自动关闭！");
            adbuilder.setCancelable(true);
            final AlertDialog dlg = adbuilder.create();
            dlg.show();
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    dlg.dismiss();
                    t.cancel();
                }
            }, 2000);
        }
    }
}

